﻿using System.Security.Cryptography;
using System.Text;

namespace AuthenticationDemo.Common
{
    internal static class CommonExtend
    {
        private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create();
        private static readonly HashSet<char> _validCharacters = new HashSet<char>(
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray()
        );
        public static string DateTimeToString(this DateTime date)
        {
            return date.ToString("yyyy-MM-dd HH:mm:ss:fff");
        }

        public static string GenerateRandomStr()
        {
            int length = 64;
            var result = new StringBuilder(length);
            while (result.Length < length)
            {
                byte[] oneByte = new byte[1];
                _rng.GetBytes(oneByte);
                char character = (char)oneByte[0];

                if (_validCharacters.Contains(character))
                {
                    result.Append(character);
                }
            }
            return result.ToString().ToUpper();
        }

        /// <summary>
        /// 将对象转换为Base64字符串
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static string StringToBase64(this string jsonStr)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(jsonStr);
            string base64 = Convert.ToBase64String(bytes).Replace('+', '-').Replace('/', '_').TrimEnd('=');
            //不允许转换为全是大写 or 小写 字母
            return base64;
        }

        /// <summary>
        /// 将Base64字符串转换回String
        /// </summary>
        /// <param name="base64String"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static string Base64ToString(this string base64String)
        {
            string base64 = base64String.Replace('-', '+').Replace('_', '/');
            switch (base64.Length % 4)
            {
                case 0: break;
                case 2: base64 += "=="; break;
                case 3: base64 += "="; break;
                default: throw new Exception("不是有效的Base-64字符串，无法正常解析！");
            }
            byte[] bytes = Convert.FromBase64String(base64);
            string jsonStr = Encoding.UTF8.GetString(bytes);
            return jsonStr;
        }
    }
}
